package com.sc.admin.common.handler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;

@ControllerAdvice
@Slf4j
public class GlobalControllerAdvice {


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {

        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }

            @Override
            public void setAsText(String text) {
                // if (xssEnable == 1) {
                //     // setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
                // } else {
                setValue(text);
                // }
            }
        });

        // Date 类型转换
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                LocalDateTime parse = null;
                try {
                    parse = LocalDateTimeUtil.parse(text, DatePattern.NORM_DATETIME_PATTERN);
                } catch (Exception e) {
                    log.error("ERROR GlobalControllerAdvice.DateUtil.parse text:{}", text);
                }
                setValue(parse);
            }
        });
    }
}
